import axios from 'axios'
import toast from 'react-hot-toast'
// const {useNavigate} = useRouter()

// axios.defaults.baseURL = 'http://8.148.80.128:3000'
axios.defaults.baseURL = 'http://localhost:3000'

// 告诉浏览器如果发送的是 post 请求，后端就一定会返回 json 格式的数据，让浏览器以解析json的方式来解析响应体
axios.defaults.headers.post['Content-Type'] = 'application/json'


// 请求 拦截器
// 在发送请求之前，判断是否有token
// 如果有token，就把token放在请求头中
// 否则，就不把token放在请求头中
axios.interceptors.request.use((request) => {
    const token = localStorage.getItem('access_token')
    if (token) {
        request.headers.Authorization = token
    }
    return request // 请求放行
})

// 响应拦截器
axios.interceptors.response.use(

    //http 状态码为200时,才走第一个回调
    response => {
        if (response.status === 200) {
            if (response.data.code !== '1') {
                toast.error(response.data.msg)
                return Promise.reject(response)
            }
        }
        return Promise.resolve(response.data);
    },
    res => {
        if (res.status === 401) {
            // console.log(res.response.data);
            toast.error(res.response.data.msg)

            const originalRequest = res.config
            // setTimeout(() => {
            //     window.location.href = '/login'
            // }, 2000)
            // 重新请求新的短 token 和长 token
            const refresh_token = localStorage.getItem('refresh_token')
            if (refresh_token) {
                axios.post('/user/refresh', {
                    refresh_token: refresh_token
                }).then(res => {
                    console.log(res);
                    if (res.code === '1') {
                        localStorage.setItem('access_token', res.access_token)
                        localStorage.setItem('refresh_token', res.refresh_token)
                        // 重新请求原请求
                        originalRequest.headers.Authorization = res.access_token
                        return axios(originalRequest)
                    }
                })
            }
        }
        if (res.status === 416) {
            // 重新登录
            localStorage.removeItem('access_token')
            localStorage.removeItem('refresh_token')
            setTimeout(() => {
                window.location.href = '/login'
            }, 2000)
        }
    }
)
export default axios